package com.hyts.serialize.binary.protobuff;

import com.hyts.serialize.binary.BinarySerializeHandler;
import io.protostuff.LinkedBuffer;
import io.protostuff.ProtostuffIOUtil;
import io.protostuff.Schema;
import io.protostuff.runtime.RuntimeSchema;

import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * project-name:coffice-toolbox
 * package-name:com.hyts.serialize.factory
 * author:Libo/Alex
 * create-date:2019-06-21 23:40
 * copyright:libo-hyts-github
 * email:libo2dev@aliyun.com
 * description:此类主要用于: protostuff 序列化功能的实现操作
 */
public class ProtobuffSerializeHandler extends BinarySerializeHandler<Object,Object> {


    /**
     * 链接buffer大小
     */
    LinkedBuffer linkedBuffer = null;

    /**
     * schema 存储对象结构池
     */
    Map<Class<?>, Schema<?>> schemaCache = null;



    @Override
    public BinarySerializeHandler<Object, Object> build() {
        linkedBuffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE);
        schemaCache = new ConcurrentHashMap<>();
        return this;
    }

    @Deprecated
    @Override
    public BinarySerializeHandler<Object, Object> build(Object param) {
        linkedBuffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE);
        schemaCache = new ConcurrentHashMap<>();
        return this;
    }


    @Override
    public byte[] serialize(Object value) {
        return (byte[]) serialize(value,Object.class);
    }


    @Override
    public <T> T deserialize(byte[] byteData, Class<T> clazz) {
        try {
            T obj = clazz.newInstance();
            Schema<T> schema = getSchema(clazz);
            ProtostuffIOUtil.mergeFrom(byteData, obj, schema);
            return obj;
        } catch (Exception e) {
            throw new IllegalStateException(e.getMessage(), e);
        }
    }

    @Override
    public <T> T serialize(T byteData, Class<T> clazzType) {
        Class<T> clazz = (Class<T>) byteData.getClass();
        Schema<T> schema = getSchema(clazz);
        byte[] data;
        try {
            data = ProtostuffIOUtil.toByteArray(byteData, schema, linkedBuffer);
        } finally {
            linkedBuffer.clear();
        }
        return (T) data;
    }

    @Override
    public Object deserialize(byte[] param) {
        return deserialize(param,Object.class);
    }



    @SuppressWarnings("unchecked")
    private <T> Schema<T> getSchema(Class<T> clazz) {
        Schema<T> schema = (Schema<T>) schemaCache.get(clazz);
        if (Objects.isNull(schema)) {
            //这个schema通过RuntimeSchema进行懒创建并缓存
            //所以可以一直调用RuntimeSchema.getSchema(),这个方法是线程安全的
            schema = RuntimeSchema.getSchema(clazz);
            if (Objects.nonNull(schema)) {
                schemaCache.put(clazz, schema);
            }
        }
        return schema;
    }
}
